package org.qengine.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.qengine.dao.PapersDao;
import org.qengine.dao.QuestionDao;
import org.qengine.entity.PapersEntity;
import org.qengine.entity.QuestionEntity;
import org.qengine.service.QuestionService;
import org.qengine.utils.Deduplicator.QuestionDeduplicator;
import org.qengine.utils.DocxParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionDao,QuestionEntity>
        implements QuestionService {

//    private String myId = "Lu";
    @Autowired
    private PapersDao papersDao;
    @Autowired
    private QuestionDao questionDao;
    private static SqlSessionFactory sqlSessionFactory;

    private static SqlSession sqlSession;

    /******新增考题******/
    @Override
    public int addQuestion(int typeID, int courseID, int knowledgeID, int dLevel, String questionStem, String questionAnswer){
        QuestionEntity questionEntity = new QuestionEntity();
        questionEntity.setTypeID(typeID);
        questionEntity.setCourseID(courseID);
        questionEntity.setKnowledgeID(knowledgeID);
        questionEntity.setDLevel(dLevel);
        questionEntity.setQuestionStem(questionStem);
        questionEntity.setQuestionAnswer(questionAnswer);
        questionEntity.setAnswerCount(0);
        questionEntity.setWrongCount(0);

        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        int flag = questionDao.addQuestion(questionEntity);
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    /******考题的批量导入******/
    public int importByJson(List<QuestionEntity> questionEntities)  {
        try{
            InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
            questionDao = sqlSession.getMapper(QuestionDao.class);

            for (QuestionEntity questionEntity : questionEntities) {
                questionDao.addQuestion(questionEntity);
            }
            sqlSession.commit();
            sqlSession.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return questionEntities.size();
    }

    /******根据id删除考题*****/
    @Override
    public int deleteQuestionById(int id) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        int flag = questionDao.deleteQuestionById(id);
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    /******根据课程与知识点删除考题*****/
    @Override
    public int deleteQuestionByCourseIdAndKnowledgeId(int courseID, int knowledgeID) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        int flag = questionDao.deleteQuestionByCourseIdAndKnowledgeId(courseID, knowledgeID);
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    /******根据id修改考题*****/
    @Override
    public int updateQuestionById(int id, int typeID, int courseID, int knowledgeID, int dLevel, String questionStem, String questionAnswer) {
        QuestionEntity questionEntity = new QuestionEntity();
        questionEntity.setId(id);
        questionEntity.setTypeID(typeID);
        questionEntity.setCourseID(courseID);
        questionEntity.setKnowledgeID(knowledgeID);
        questionEntity.setDLevel(dLevel);
        questionEntity.setQuestionStem(questionStem);
        questionEntity.setQuestionAnswer(questionAnswer);
        questionEntity.setAnswerCount(0);
        questionEntity.setWrongCount(0);

        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        int flag = questionDao.updateQuestionById(questionEntity);
        if (flag == 0) {
            questionDao.addQuestionWithId(questionEntity);
        }
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    @Override
    public QuestionEntity getQuestionById(int id) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);
        List<QuestionEntity> questionEntities = questionDao.getQuestionById(id);
        if(questionEntities.isEmpty()) {
            sqlSession.close();
            return null;
        }
        QuestionEntity questionEntity = questionEntities.get(0);
        sqlSession.close();
        return questionEntity;
    }

    @Override
    public List<String> findStemAndAnswerById(int id) {
        List list = new ArrayList<String>();
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        List<QuestionEntity> questionEntities = questionDao.getQuestionById(id);
        QuestionEntity questionEntity = questionEntities.get(0);

        if(questionEntity != null) {
            list.add(questionEntity.getQuestionStem());
            list.add(questionEntity.getQuestionAnswer());
            sqlSession.close();
            return list;
        }else{
            sqlSession.close();
            return null;
        }

    }

    /******根据课程id删除考题*****/
    @Override
    public int deleteQuestionByCourseId(int courseId) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        int flag = questionDao.deleteQuestionByCourseId(courseId);
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    /******根据课程查询考题*****/
    @Override
    public List<QuestionEntity> selectQuestionByCourseId(int courseID) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        List<QuestionEntity> questions = questionDao.selectQuestionByCourseId(courseID);

        sqlSession.commit();
        sqlSession.close();
        return questions;
    }

    /******考题去重****/
    @Override
    public List<Integer> DeduplicationQuestion() {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);
        List<QuestionEntity> questionList = questionDao.selectAllQuestions();
        List<Integer> deletedIds = QuestionDeduplicator.deduplicate(questionList);
        if(!deletedIds.isEmpty()) {

            for (Integer deletedId : deletedIds) {
                questionDao.deleteQuestionById(deletedId);
            }
        }
        sqlSession.commit();
        sqlSession.close();
        return deletedIds;
    }

    /******对应课程考题去重****/
    @Override
    public List<Integer> DeduplicationQuestionByCourseId(int CourseId) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);

        List<QuestionEntity> questionList = questionDao.selectQuestionByCourseId(CourseId);
        List<Integer> deletedIds = QuestionDeduplicator.deduplicate(questionList);
        if(!deletedIds.isEmpty()) {

            for (Integer deletedId : deletedIds) {
                questionDao.deleteQuestionById(deletedId);
            }


        }
        sqlSession.commit();
        sqlSession.close();
        return deletedIds;
    }

    @Override
    public List<QuestionEntity> dynamicSelect(@Param("typeId") Integer typeId, @Param("courseId") Integer courseId, @Param("knowledgeId") Integer knowledgeId, @Param("dLevel") Integer dLevel) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);
        Map<String,Object> body = new HashMap<>();
        if(typeId != null){
            body.put("typeId",typeId);
        }
        if(courseId != null){
            body.put("courseId",courseId);
        }
        if(knowledgeId != null){
            body.put("knowledgeId",knowledgeId);
        }
        if(dLevel != null){
            body.put("dLevel",dLevel);
        }
        List<QuestionEntity> questions =  questionDao.selectQuestionByDynamicRules(body);
        sqlSession.close();
        return questions;
    }


    public static void main(String[] args) {
        QuestionService questionService = new QuestionServiceImpl();
        QuestionEntity questionEntity = questionService.getQuestionById(1);
        System.out.println(questionEntity);
    }

    @Override
    public int importByDoc(InputStream docInputStream, Integer courseId) {
        InputStream inputStream = QuestionServiceImpl.class.getClassLoader().getResourceAsStream("questionMapper/question-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        questionDao = sqlSession.getMapper(QuestionDao.class);
        int num = 0;
        try {
            List<QuestionEntity> questions = new DocxParser().parseDocx(docInputStream, courseId);
            num = questions.size();
            for (QuestionEntity question : questions) {
                questionDao.addQuestion(question);
            }
            sqlSession.commit();
            sqlSession.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }
    @Override
    public String testMarks(String list,Long paperId){

       try {

           PapersEntity papersEntity = papersDao.findById(paperId);
           Long[] questionIds = papersDao.findById(paperId).getQuestionIdsAsArray();
           for (int i = 0; i < questionIds.length; i++) {
               QuestionEntity questionEntity = questionDao.getQuestionById(questionIds[i].intValue()).get(0);
               if (list.charAt(i) == '0') {
                   questionEntity.setWrongCount(questionEntity.getWrongCount() + 1);
               }
               questionEntity.setAnswerCount(questionEntity.getAnswerCount() + 1);
               questionDao.updateQuestionById(questionEntity);
           }
           return "success";
       }catch (Exception e){
           e.printStackTrace();
       }
       return "fail";
    }
}

